package com.kl.airticketserver.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.kl.airticketserver.dto.Result;
import com.kl.airticketserver.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SaTokenConfig {
    
    private static final Logger log = LoggerFactory.getLogger(SaTokenConfig.class);
    
    @Autowired
    private AuthProperties authProperties;


    /**
     * 注册Sa-Token全局过滤器
     */
    @Bean
    public SaServletFilter getSaReactorFilter() {
        return new SaServletFilter()
                // 指定 拦截路由 与 放行路由
                .addInclude("/**").setExcludeList(authProperties.getSkipUrls())    /* 排除掉 /favicon.ico */
                // 鉴权方法：每次访问进入
                .setAuth(obj -> {
                    // 对于OPTIONS预检请求直接放行
                    SaRouter.match(SaHttpMethod.OPTIONS).stop();
                    StpUtil.checkLogin();
                })
                // setAuth方法异常处理
                .setError(this::handleException);
    }

    /**
     * 自定义异常处理
     *
     * @param e
     * @return
     */
    private String handleException(Throwable e) {
        //设置错误返回格式为JSON
        if (e instanceof NotLoginException) {
            return JsonUtil.toJsonString(Result.error(403, "未登录"));
        } else if (e instanceof NotPermissionException) {
            return JsonUtil.toJsonString(Result.error(405, "无权限操作"));
        } else {
            return JsonUtil.toJsonString(Result.error(406, "授权异常"));
        }
    }

}